/**
 * 平台管理系统--字典管理
 * @author 卢凤丹
 */
import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {DictionaryService} from './dictionary.service';
import {CopyUtil} from '../../../utils/copy.util';
import {StatusEnum} from '../../../core/enum/status.enum';
import {FilterEnum, FilterTypeEnum} from '../../../core/enum/filter.enum';
import {NzMessageService} from 'ng-zorro-antd';
import {OtherUtil} from '../../../utils/other.util';

@Component({
    selector: 'app-dictionary',
    templateUrl: './dictionary.component.html',
    styleUrls: ['./dictionary.component.scss'],
    providers: [DictionaryService]
})
export class DictionaryComponent implements OnInit {

    searchLabel = '';
    searchDesc = '';
    pageInfo: PageEntity = new PageEntity();
    allList: ExciseList[] = [];
    displayList = [];
    mapOfCheckedId: { [key: string]: boolean } = {};
    isAllCheck = false;
    isIndeterminate = false;

    isAdd = true;
    showAddModal = false; // 新增弹框
    oneObj: DicObj = new DicObj();
    validateForm: FormGroup;
    canDelete = true;

    constructor(
        private service: DictionaryService,
        private message: NzMessageService,
        private fb: FormBuilder
    ) {
    }

    ngOnInit() {
        this.pageInfo.multiSortMeta = [
            {
                field: 'type',
                order: 1
            },
            {
                field: 'orderLevel',
                order: 1
            }
        ];
        this.getPage();
        this.initForm();
    }

    initForm() {
        this.validateForm = this.fb.group({
            keyCode: [null, [Validators.required]],
            keyValue: [null, [Validators.required]],
            orderLevel: [0, [Validators.required]],
            type: [null, [Validators.required]],
            description: [null, []]
        });
    }

    /**
     * 分页过滤逻辑搜索处理
     * @param pageConfig:当前分页对象
     * @param currVal:前端传入值
     * @param acceptVal:后台接受字段
     * @param mode:匹配没模式
     * @param type:搜索类型
     */
    dealComFilterLogic(pageConfig: PageEntity, currVal: any, acceptVal: any, mode: any, type: any): void {
        pageConfig.filters[acceptVal.toString()] = currVal ? {
            matchMode: mode,
            value: currVal,
            whereType: type
        } : undefined;

    }

    // 点击查询
    clickSearch() {
        this.pageInfo.first = 1;
        this.dealComFilterLogic(this.pageInfo, this.searchLabel, 'type', FilterEnum.CONTAINS, FilterTypeEnum.AND);
        this.dealComFilterLogic(this.pageInfo, this.searchDesc, 'description', FilterEnum.CONTAINS, FilterTypeEnum.AND);
        // if (this.searchDesc) {
        //     this.pageInfo.filters['description'.toString()] = {
        //         matchMode: FilterEnum.CONTAINS,
        //         value: this.searchDesc,
        //         whereType: FilterTypeEnum.AND
        //     };
        // } else {
        //     this.pageInfo.filters['description'.toString()] = undefined;
        // }
        this.getPage();
    }

    // 点击重置
    resetSearch() {
        this.pageInfo.first = 1;
        this.searchLabel = null;
        this.searchDesc = null;
        this.pageInfo.filters['type'.toString()] = undefined;
        this.pageInfo.filters['description'.toString()] = undefined;
        this.getPage();
    }

    // 分页查询
    getPage() {
        this.service.page(this.pageInfo).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.allList = res.datas.data;
                this.pageInfo.totalRecords = res.datas.totalRecords;
            }
        });
    }

    // 第几页
    searchPageIndex(event) {
        this.pageInfo.first = event;
        this.getPage();
    }

    // 每页几条
    searchPageSize(event) {
        this.pageInfo.rows = event;
        this.pageInfo.first = 1;
        this.getPage();
    }

    currentPageDataChange($event): void {
        this.displayList = $event;
        this.refreshStatus();
    }

    refreshStatus(): void {
        this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
        this.isIndeterminate =
            this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
            !this.isAllCheck;
        this.checkDelete();
    }

    checkDelete(): void {
        if (OtherUtil.deleteIds(this.mapOfCheckedId).length > 0) {
            this.canDelete = false;
        } else {
            this.canDelete = true;
        }
    }

    checkAll(value: boolean): void {
        this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
        this.refreshStatus();
    }

    // 点击删除一个
    deleteOne(id) {
        this.service.delete([id]).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.mapOfCheckedId = {};
                // this.pageInfo.first = 1;
                this.getPage();
            }
        });
    }

    // 删除所选
    deleteAll() {
        const arr = [];
        for (const val in this.mapOfCheckedId) {
            if (this.mapOfCheckedId[val]) {
                arr[arr.length] = val;
            }
        }
        if (arr.length < 1) {
            this.message.warning('请勾选要删除的数据!');
            return;
        }
        this.service.delete(arr).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.mapOfCheckedId = {};
                this.pageInfo.first = 1;
                this.getPage();
            }
        });
    }

    cancelFn(): void {
        this.canDelete = true;
        this.isAllCheck = false;
        this.mapOfCheckedId = {};
        this.isIndeterminate = false;
    }

    // 点击新增
    clickAdd() {
        this.initForm();
        this.isAdd = true;
        this.oneObj = new DicObj();
        this.showAddModal = true;
    }

    dealAddSub(): void {
        this.service.create(this.oneObj).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.showAddModal = false;
                this.getPage();
            }
        });
    }

    dealEditSub(): void {
        this.service.update(this.oneObj).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.showAddModal = false;
                this.getPage();
            }
        });
    }

    // 新增确认
    handleOk() {
        this.isAdd ? this.dealAddSub() : this.dealEditSub();
    }

    // 点击编辑
    editUser(obj) {
        this.isAdd = false;
        this.oneObj = CopyUtil.deepCopy(obj, {});
        this.showAddModal = true;
    }

    // 点击添加键值
    addType(val) {
        this.isAdd = true;
        this.showAddModal = true;
        this.oneObj = new DicObj();
        this.oneObj.type = val;
    }
}

export class DicObj {
    description?: string;
    id?: string;
    keyCode?: string;
    keyValue?: string;
    orderLevel?: number;
    type?: string;
}

// 试题obj
export class ExciseList {
    id?: string;
    type?: number;
    content?: string;
    resourceTypeName?: string;
    label?: number;
    operator?: string;
    gmtCreate?: string;
}
